package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Reference
    private PermissionService permissionService;

    @RequestMapping("/add.do")
    public Result add(@RequestBody Permission permission) {
        try {
            permissionService.add(permission);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "权限添加失败");
        }
        return new Result(true, "权限添加成功");
    }

    @RequestMapping("/findPage.do")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

        return permissionService.findPage(queryPageBean);
    }

    //权限校验
    @RequestMapping("/delete.do")
    public Result delete(Integer id) {
        try {
            permissionService.delete(id);
        } catch (RuntimeException e){
            return new Result(false, e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "权限删除失败");
        }
        return new Result(true, "权限删除成功");
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody Permission permission) {
        try {
            permissionService.edit(permission);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "权限编辑失败");
        }
        return new Result(true,"权限编辑成功");
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Permission permission = permissionService.findById(id);
            return new Result(true, "权限查询成功", permission);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "权限查询失败");
        }
    }

    @RequestMapping("/findAll")
    public Result findAll() {
        List<Permission> all = permissionService.findAll();
        if (all != null && all.size() != 0) {
            return new Result(true,"权限查询成功", all);
        }
        return new Result(false, "权限查询失败");
    }
}
